import Url2File from './Url2File.js'

export default {
  /**  @description 合并遮罩图：仅限黑白遮罩图
   * @param { number } width - 图片宽度
   * @param { number } height - 图片高度
   * @param { array } images - 遮罩图片列表
   * @param { boolean } canNotImages - 没有遮罩图片时，允许不合成遮罩
   * @param { string } type - 返回的数据格式：image | blob | base64
   * @param { function } success - 成功后返回方法
   * @param { function } fail - 错误返回方法
   * 
  */
  mergeMark(param = {}) {
    let images = param.images || []
    if (images.length == 0 && !param.canNotImages) {
      param.fail('没有遮罩图片可合并')
      return false
    }
    let canvas = document.createElement('canvas');
    canvas.type = '2d';
    canvas.width = param.width;
    canvas.height = param.height;
    let ctx = canvas.getContext('2d');
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    // 读取全部遮罩
    const markList = images.map((v) => 
      this.getImageInfo(v)
    )
    Promise.all(markList).then(res => {
      const drawMarkList = res.map((img) => 
        this.drawOneMark(img, ctx)
      )
      Promise.all(drawMarkList).then(res2 => {
        this.canvasToFile(canvas, param.type, (image) => {
          param.success(image)
          canvas.remove()
        })
      })
    }).catch((err) => {
      param.fail('遮罩图片读取失败')
    })
  },
  drawOneMark(img, ctx) {
    return new Promise((resolve, reject) => {
      let imgCanvas = document.createElement('canvas');
      imgCanvas.width = img.width;
      imgCanvas.height = img.height;
      let imgCtx = imgCanvas.getContext('2d');
      imgCtx.drawImage(img, 0, 0);
      let imgData = imgCtx.getImageData(0, 0, img.width, img.height);
      let data = imgData.data;
      // 去除底色
      for (let i2 = 0; i2 < data.length; i2 += 4) {
        let r = data[i2 + 0];
        let g = data[i2 + 1];
        let b = data[i2 + 2];
        let a = data[i2 + 3];
        if (r == 0 && g == 0 && b == 0) {
          a = 0;
        } else if (r == g && g == b) {
          a = 255 * (255  / (255 - r));
        }
        data[i2 + 3] = a;
      }
      imgCtx.putImageData(imgData, 0, 0);
      this.canvasToFile(imgCanvas, 'image', (image) => {
        ctx.drawImage(image, 0, 0);
        imgCanvas.remove();
        resolve(true)
      })
    })
  },
  // 生成图片
  canvasToFile(canvas, type='image', callBack=()=>{}) {
    let minImg = canvas.toDataURL();
    if (type == 'base64') {
      callBack(minImg)
      return
    }
    let blob = Url2File.base64toBlob(minImg);
    let reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      if (type == 'blob') {
        callBack(reader.result)
      } else {
        let tmpImg = new Image();
        tmpImg.src = reader.result;
        tmpImg.onload = () => {
          callBack(tmpImg)
        }
      }
    }
  },
  /* 读取图片信息 */
  getImageInfo(url) {
    return new Promise((resolve, reject) => {
      const img = new Image(); // 创建图片对象
      img.setAttribute('crossOrigin', 'anonymous')
      img.src = url;
      img.onload = (imgInfo) => {
        resolve(img);
      }
      img.onerror = (err) => {
        reject(err)
      }
    })
  },

  /** 镂空并填充颜色：仅黑白图片去除黑色部分 */
  hollowOut(src, rgba = [64,56,124,1]) {
    return new Promise((resolve, reject) => {
      let canvas = document.createElement('canvas'),
          img = new Image()

      img.setAttribute('crossOrigin', 'anonymous')
      img.src = src
      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext('2d',{willReadFrequently:true})
        ctx.drawImage(img, 0, 0)
        let imgData = ctx.getImageData(0, 0, img.width, img.height)
        let data = imgData.data
        // 去除底色
        for (let i2 = 0; i2 < data.length; i2 += 4) {
          let r = data[i2 + 0];
          let g = data[i2 + 1];
          let b = data[i2 + 2];
          let a = data[i2 + 3];
          if (r == 0 && g == 0 && b == 0) {
            a = 0;
          } else if (r == g && g == b) {
            r = rgba[0]
            g = rgba[1]
            b = rgba[2]
          } else {
            a = 255 - r
          }
          data[i2 + 0] = r;
          data[i2 + 1] = g;
          data[i2 + 2] = b;
          data[i2 + 3] = a;
        }
        ctx.putImageData(imgData, 0, 0)
        let newMarkImage = canvas.toDataURL()
        canvas.remove()
        img.remove()
        resolve(newMarkImage)
      }
      img.onerror = (err) => {
        reject(err)
      }
    })
  }
}
